package com.cskaoyan.service.impl;

import com.cskaoyan.bean.bo.GoodsCreateAndUpdateBO;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;

import com.cskaoyan.mapper.*;
import com.cskaoyan.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商品管理-商品管理
 * 创建日期: 2022/04/07 22:23
 *
 * @author HanWeiqi
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    // 目录
    @Autowired
    MarketCategoryMapper  marketCategoryMapper;

    // 品牌商
    @Autowired
    MarketBrandMapper marketBrandMapper;



    // 获取商品列表
    @Override
    @Transactional
    public GoodsListVO goodsList(BaseParam baseParam, Integer goodsId, String goodsSn, String name) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        if(goodsId!=null){
            criteria.andIdEqualTo(goodsId);
        }
        if(goodsSn!=null && !"".equals(goodsSn)){
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if(name!=null && !"".equals(name)){
            criteria.andNameLike("%"+name+"%");
        }

        criteria.andDeletedEqualTo(false);

        if(baseParam.getOrder()!=null && baseParam.getSort()!=null){
            marketGoodsExample.setOrderByClause(baseParam.getSort()+" "+baseParam.getOrder());
        }

        if(baseParam.getPage()!=null && baseParam.getLimit() !=null){
            PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
        }
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);

        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoods);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        if(baseParam.getLimit()==0){
            pages=0;
            baseParam.setPage(0);
        }

        return GoodsListVO.data(total, pages, baseParam.getPage(), baseParam.getLimit(), marketGoods);
    }

    // 商品删除
    @Override
    public int goodsDelete(MarketGoods marketGoods) {
        marketGoods.setDeleted(true);
        return marketGoodsMapper.updateByPrimaryKeyWithBLOBs(marketGoods);
    }

    // 商品添加
    @Override
    @Transactional
    public void goodsCreate(GoodsCreateAndUpdateBO createBO) {
        MarketGoods marketGoods = createBO.getGoods();
        List<MarketGoodsProduct> products = createBO.getProducts();
        List<MarketGoodsAttribute> attributes = createBO.getAttributes();
        List<MarketGoodsSpecification> specifications = createBO.getSpecifications();


        BigDecimal lowPrice = BigDecimal.valueOf(0.0);
        for (MarketGoodsProduct product : products) {
            lowPrice = product.getPrice();
            if(lowPrice.doubleValue() >= product.getPrice().doubleValue()){
                lowPrice = product.getPrice();
            }
        }

        // 向market_goods表中插入数据
        marketGoods.setAddTime(new Date());
        marketGoods.setUpdateTime(new Date());
        marketGoods.setRetailPrice(lowPrice);
        marketGoodsMapper.insertSelective(marketGoods);

        // 向market_goods_product表中插入数据
        for (MarketGoodsProduct product : products) {
            product.setId(null);
            product.setAddTime(new Date());
            product.setUpdateTime(new Date());
            product.setGoodsId(marketGoods.getId());
            marketGoodsProductMapper.insertSelective(product);
        }


        // 向market_goods_attribute表中插入数据
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setAddTime(new Date());
            attribute.setUpdateTime(new Date());
            attribute.setGoodsId(marketGoods.getId());
            marketGoodsAttributeMapper.insertSelective(attribute);
        }


        // 向market_goods_specification表中插入数据
        for (MarketGoodsSpecification specification : specifications) {
            specification.setAddTime(new Date());
            specification.setUpdateTime(new Date());
            specification.setGoodsId(marketGoods.getId());
            marketGoodsSpecificationMapper.insertSelective(specification);
        }

    }


    @Override
    @Transactional
    public CatAndBrandVO catAndBrand() {
        // 1,获取目录
        MarketCategoryExample example = new MarketCategoryExample();
        MarketCategoryExample.Criteria criteria = example.createCriteria();
        // 查找一级目录且deted为0
        criteria.andLevelEqualTo("L1").andDeletedEqualTo(false);
        // 一级目录,全部
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(example);

        // 最后封装到 list 里面 -----> 返回的变量1
        List<CatAndBrandVO.CategoryListDTO> categoryListDTOS = new ArrayList<>();


        //
        for (MarketCategory marketCategory : marketCategories) {

            // 新建 目录类
            CatAndBrandVO.CategoryListDTO categoryListDTO = new CatAndBrandVO.CategoryListDTO();

            // 1, 获取当前一级目录id 找 一级id与父级id相同的
            Integer id = marketCategory.getId();
            MarketCategoryExample example2Second = new MarketCategoryExample();
            MarketCategoryExample.Criteria criteria2Second = example2Second.createCriteria();
            criteria2Second.andPidEqualTo(id).andDeletedEqualTo(false);

            // 2, 获取 二级目录
            List<MarketCategory> marketCategories2Second = marketCategoryMapper.selectByExample(example2Second);

            List<CategoryL1InnerIdAndName> categoryL1InnerIdAndNames = new ArrayList<>();
            // 3, 遍历二级目录 --> 封装 二级目录的id与name
            for (MarketCategory category : marketCategories2Second) {
                categoryL1InnerIdAndNames.add(new CategoryL1InnerIdAndName(category.getId(), category.getName()));

            }
            // 4, 获取一级类目 属性
            Integer id2First = marketCategory.getId();
            String name2First = marketCategory.getName();
            // 5, set进去
            categoryListDTO.setValue(id2First);
            categoryListDTO.setLabel(name2First);
            categoryListDTO.setChildren(categoryL1InnerIdAndNames);
            // 6, 每一个都封装 list
            categoryListDTOS.add(categoryListDTO);
        }


        // 2,获取品牌商名称
        MarketBrandExample marketBrandExample = new MarketBrandExample();

        MarketBrandExample.Criteria criteria2Brand = marketBrandExample.createCriteria();

        criteria2Brand.andDeletedEqualTo(false);

        List<MarketBrand> marketBrands = marketBrandMapper.selectByExample(null);

        // 品牌商list --------> 返回的变量2
        List<CategoryL1InnerIdAndName> categoryL1InnerIdAndNames = new ArrayList<>();

        for (MarketBrand marketBrand : marketBrands) {
            categoryL1InnerIdAndNames.add(new CategoryL1InnerIdAndName(marketBrand.getId(), marketBrand.getName()));
        }

        // 3, 返回一个
        return new CatAndBrandVO(categoryListDTOS,categoryL1InnerIdAndNames);
    }


    @Override
    @Transactional
    public GoodsDetailVO detail(Integer id) {
        // 获取商品的所有goods信息，对应GoodsDetailVO的goods
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);

        // 获取商品的所有categoryId，对应GoodsDetailVO的categoryIds
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria category = marketCategoryExample.createCriteria();
        category.andDeletedEqualTo(false);
        category.andIdEqualTo(marketGoods.getCategoryId());
        List<Integer> categoryIds = new ArrayList<>();
        categoryIds.add(marketGoods.getCategoryId());
        List<MarketCategory> marketCategories = marketCategoryMapper.selectByExample(marketCategoryExample);
        for (MarketCategory marketCategory : marketCategories) {
            categoryIds.add(marketCategory.getPid());
        }



        // 根据goodsId获取商品的所有参数，对应GoodsDetailVO的attributes
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria attribute = marketGoodsAttributeExample.createCriteria();
        attribute.andGoodsIdEqualTo(id);
        attribute.andDeletedEqualTo(false);
        List<MarketGoodsAttribute> marketGoodsAttributes = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);

        // 根据goodsId获取商品的所有库存，对应GoodsDetailVO的attributes
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria product = productExample.createCriteria();
        product.andGoodsIdEqualTo(id);
        product.andDeletedEqualTo(false);
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(productExample);

        // 根据goodsId获取商品的规格信息，对应GoodsDetailVO的specifications
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria specification = marketGoodsSpecificationExample.createCriteria();
        specification.andGoodsIdEqualTo(id);
        specification.andDeletedEqualTo(false);
        List<MarketGoodsSpecification> marketGoodsSpecifications = marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);

        return new GoodsDetailVO(marketGoods,categoryIds,marketGoodsAttributes,marketGoodsProducts,marketGoodsSpecifications);
    }

    @Override
    @Transactional
    public void goodsUpdate(GoodsCreateAndUpdateBO createBO) {
        MarketGoods marketGoods = createBO.getGoods();
        List<MarketGoodsProduct> products = createBO.getProducts();
        List<MarketGoodsAttribute> attributes = createBO.getAttributes();
        List<MarketGoodsSpecification> specifications = createBO.getSpecifications();

        // 根据id更新market_goods表中数据
        marketGoods.setUpdateTime(new Date());
        marketGoodsMapper.updateByPrimaryKeySelective(marketGoods);


        // 根据id更新market_goods_attribute表中数据
        for (MarketGoodsProduct product : products) {
            product.setUpdateTime(new Date());
            marketGoodsProductMapper.updateByPrimaryKeySelective(product);
        }

        // 根据id更新market_goods_product表中数据
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setUpdateTime(new Date());
            marketGoodsAttributeMapper.updateByPrimaryKeySelective(attribute);
        }


        // 根据id更新market_goods_specification表中数据
        for (MarketGoodsSpecification specification : specifications) {
            specification.setUpdateTime(new Date());
            marketGoodsSpecificationMapper.updateByPrimaryKeySelective(specification);
        }
    }
}
